﻿using MobileControlGuru.Base;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using MobileControlGuru.Tools;
using MobileControlGuru.Src;
using static MobileControlGuru.AutoTask.TaskRun;
using System.Windows.Forms;
using System.Web.UI.WebControls;
using static MobileControlGuru.AutoTask.TaskJson;
using System.Text.RegularExpressions;

namespace MobileControlGuru.AutoTask
{
    public class TaskRun
    {
        TaskJson.TaskInfo taskInfo;
        string DeviceName;
        bool Debug = false;

        public delegate void TaskStartDelegate();
        public delegate void TaskFinishedDelegate();

        public delegate void TaskSingleEndDelegate(string cmd);
        public delegate void TaskSingleStartDelegate(string cmd);

        //任务开始委托
        public TaskStartDelegate taskStartDelegate;
        //任务结束委托
        public TaskFinishedDelegate taskFinishedDelegate;

        //单条指令开始
        public TaskSingleStartDelegate singleStartDelegate;
        //单条指令结束 
        public TaskSingleEndDelegate singleEndDelegate;
        public CancellationTokenSource cts = new CancellationTokenSource();
        public TaskRun(string deviceName, TaskJson.TaskInfo taskInfo, bool debug = false)
        {
            DeviceName = deviceName;
            this.taskInfo = taskInfo;
            Debug = debug;
        }
        //文件名特殊字符替换
        static string ValidateAndReplaceSpecialChars(string fileName)
        {
            // 定义不允许的特殊字符正则表达式
            string pattern = @"[\\/:*?""<>|]";

            // 使用正则表达式替换特殊字符为 _
            return Regex.Replace(fileName, pattern, "_");
        }
        public string R(TaskJson.TaskItem taskItem)
        {
            try
            { 
          
                if (singleStartDelegate != null)
                    singleStartDelegate(taskItem.Oprate + " " + taskItem.Param);
                string res = "";
                
                if (taskItem.IsAdb)
                {
                   
                    //特殊脚本 处理
                    if (taskItem.Oprate == "shell screencap")
                    {
                        string cmd = "";
                        string screenshot = this.taskInfo.DeviceName.FirstOrDefault() +"_"+this.taskInfo.Name+"_"+DateTime.Now.ToString("yyyyMMddHHmmss") + ".png";
                        screenshot = ValidateAndReplaceSpecialChars(screenshot);
                        cmd = "-s " + DeviceName + $" shell screencap -p /sdcard/{screenshot} ";
                        var adb1 = ADB.Exec(cmd);

                        string pullcmd = "-s " + DeviceName + $" pull /sdcard/{screenshot} "+ taskItem.Param;
                        var adb2 = ADB.Exec(pullcmd);
                    }
                    else
                    {
                        string cmd = "";
                        cmd = "-s " + DeviceName + " " + taskItem.Oprate + " " + taskItem.Param;
                        var adb = ADB.Exec(cmd);
                        res = adb.Message;


                        Console.WriteLine($"{cmd} ：{DateTime.Now}");
                    }
                }
                else
                {
                    if (taskItem.Oprate == "sleep")
                    {

                        Thread.Sleep(Convert.ToInt32(taskItem.Param));
                    }
                    else
                    {

                        res = CMD.Exec(taskItem.Param);

                    }
                }
                if (singleEndDelegate != null)
                    singleEndDelegate(res);


                
                return res;
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, taskItem.Oprate + "" + taskItem.Param);
                //singleEndDelegate("run error"+ ex.Message);
                return ex.Message;
            }


        }

        public void Run()
        {

            if (taskStartDelegate != null)
            {
                taskStartDelegate();
            }
            if (Debug)
            {
                foreach (var t in taskInfo.TaskItems)
                {
                    if (cts.Token.IsCancellationRequested)
                    {
                        break;
                    }
                    R(t);
                }
               
           

            }
            else
            {
                int i = taskInfo.RunTimes;
                while (i != 0)
                {
                    foreach (var t in taskInfo.TaskItems)
                    {
                        if (cts.Token.IsCancellationRequested)
                        {
                            break;
                        }
                        R(t);
                    }
                    i--;
                }
               
            }
            if (taskInfo.Type == TaskJson.TaskTypeEnum.datetime)
            {
                taskInfo.State = TaskJson.TaskStateEnum.done;
                Console.WriteLine($"task is done ：{DateTime.Now}--{taskInfo.Name}-{taskInfo.id}");
                TaskManager.Instance.JobDelete(taskInfo);
                //
                TaskJson.DelTask(taskInfo.id);

                //

            }

            if (taskFinishedDelegate != null)
            {
                taskFinishedDelegate();
            }
        }

        public async Task RunAsync()
        {
            using (HttpClient client = new HttpClient())
            {
                string website = "https://www.example.com";
                string content = await client.GetStringAsync(website);
                Console.WriteLine("下载内容长度：" + content.Length);
            }
        }
    }
}
